
import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList, Animated, View, Image, TouchableOpacity, Alert, TextInput
} from "react-native";
import { NavigationEvents, ScrollView } from 'react-navigation';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ApprovalCpt } from '../_components/ApprovalCpt';
import MethodUtil from '../../../utils/MethodUtil';
import ToastUtil from '../../../utils/toast';
import Utils from '../../../utils/utils';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';

const scale = GLOBAL.SCALE;
const correct = require('../../../imgs/global/correct.png')
const titleImgObj = require('../../../imgs/global/down.png');
let upDegreen = require('../../../imgs/my-siter/up.png');
let downDegreen = require('../../../imgs/my-siter/down.png');

export class NonWholePackDetail extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '成交申请详情',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		let { data, applyInfo, salesType } = props.navigation.state.params || {};
		this.state = {
			status: 'data',
			refreshIcon: false,
			allText: '',
			showRejectModal: false
		}
		this.data = data
		this.applyParams = {
			applyInfo: applyInfo,
			itemList: []
		}
		this.salesType = salesType
		this.selectData = {};
	}

	async componentWillMount() {
		// await this.initPage();
	}
	//初始化数据
	initPage = async () => {

	}
	changeCheck = (index) => {
		let { isAll } = this.state;
		let { appOrderDetailsVTOS } = this.data
		appOrderDetailsVTOS[index].select = !appOrderDetailsVTOS[index].select
		appOrderDetailsVTOS.map((item, i) => {
			if (appOrderDetailsVTOS[index].select === false && i > index) {
				item.select = false
			}
			else if (appOrderDetailsVTOS[index].select === true && i < index) {
				item.select = true
			}
			if (!item.select) {
				isAll = false
			}
			else {
				isAll = true
			}
		})
		this.setState({
			isAll
		}, () => {
			this.bottomText()
		});
	}
	//全选方法
	_selectAll = (isAll) => {
		let { appOrderDetailsVTOS } = this.data
		appOrderDetailsVTOS.map((item) => {
			item.select = isAll
		})
		this.setState({
			isAll
		}, () => {
			this.bottomText()
		});
	}
	bottomText = () => {
		let { appOrderDetailsVTOS } = this.data
		let num = 0, qty = 0, allText;
		appOrderDetailsVTOS.map((item) => {
			if (item.select) {
				num++;
				qty += parseInt(item.intentionQuantity || 0)
			}
		})
		if (num == 0) {
			allText = ''
		}
		else {
			allText = '选择' + num + '条,' + qty + '吨'
		}

		this.setState({
			allText
		})
	}
	_refused = () => {
		this.applyParams.applyInfo.applyType = 'REJECT'
		this._showAlert()
	}
	_showAlert = async () => {
		let { appOrderDetailsVTOS } = this.data
		this.applyParams.itemList = []
		appOrderDetailsVTOS.map((item) => {
			if (item.select == true) {
				this.applyParams.itemList.push(
					{
						bidOrderId: item.bidOrderId,
						intentionQuantity: item.intentionQuantity,
						resourceId: item.resourceId
					}
				)
			}
		})
		if (this.applyParams.itemList.length === 0) {
			ToastUtil.showWarning('请选择成交对象');
			return
		}
		let responese = await HTTP.POST(API_GENERATE(API.PACKAGE_TOAST), this.applyParams);
		if (responese) {
			this.priceCheckMsg = responese.priceCheckMsg
			this.setState({
				showRejectModal: true
			})
		}
	}
	_add = () => {
		let { appOrderDetailsVTOS } = this.data
		this.goBack = true
		appOrderDetailsVTOS.map((item, index) => {
			if (item.intentionQuantity <= 0) {
				ToastUtil.showWarning('成交执行量必须为正');
				this.goBack = false
			}
			if (this.goBack) {
				this.props.navigation.state.params.callback(this.data)
				this.props.navigation.goBack()
			}
		})
	}
	approve = async () => {
		this.setState({
			showRejectModal: false,
		})

		let res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_APPLY), this.applyParams);
		if (res) {
			this.setState({
				status: 'data',
			}, () => {
				ToastUtil.showSuccess(this.applyParams.applyInfo.applyType === 'ACCEPT' ? '审批成功' : '驳回成功').then(() => {
					this._goBack();
				})
			})
		}
	}
	_goBack = () => {
		this.props.navigation.navigate('ClinchRecord', {
			bidPackageId: this.applyParams.applyInfo.bidPackageId, bizModel: 'Z', winRule: 'SINGLE', salesType: this.salesType
		})
	}

	render() {
		let { isAll, allText, showRejectModal } = this.state;
		let { priceType, appOrderDetailsVTOS, chineseName, custPurNum, offerBottomPrice, suggestedPrice, udPrice, areaIdName } = this.data
		return (
			<View style={styles.container}>
				<View style={styles.body}>
					<View style={styles.itemTop}>
						<View style={styles.itemTitle}>
							<View style={styles.itemTopLeft}>
								<Text style={{ color: '#040404', fontWeight: '600' }}>{chineseName}</Text>
							</View>
						</View>
						<View style={[styles.itemTitle, { paddingLeft: 10 * scale, marginTop: 12 * scale }]}>
							<Text style={styles.titleText}>数量 {custPurNum} 吨</Text>
							<View style={{ flexDirection: "row", alignItems: 'center' }}>
								{priceType == 1 ?
									<Text style={styles.titleText}>报盘底价 ¥ {MethodUtil.toThousands(offerBottomPrice || 0, 2) || '-'} 元/吨 </Text> :
									<Text style={styles.titleText}>{udPrice > 0 ? '+' : ''}¥{MethodUtil.toThousands(udPrice || 0, 2)} 元/吨 </Text>
								}
								<Text style={[styles.priceType, priceType == 2 ? { color: '#FA6400', backgroundColor: '#FBEFE8' } : { color: '#85C0EC', backgroundColor: '#ECF7FF' }]}>
									{priceType == 2 ? '升贴水' : '一口价'}
								</Text>
							</View>
						</View>
						<View style={[styles.itemTitle, { paddingLeft: 10 * scale, marginTop: 12 * scale }]}>
							{suggestedPrice && priceType == 1 ?
								<Text style={styles.titleText}>{areaIdName}现货价：¥{suggestedPrice ? MethodUtil.toThousands(suggestedPrice || '0') : null}/吨 </Text>
								: null
							}
						</View>
					</View>
					<ScrollView style={{ marginLeft: 20 * scale, marginRight: 20 * scale }}>
						{appOrderDetailsVTOS.length > 0 ? appOrderDetailsVTOS.map((item, index) => {
							let price
							if (priceType == 2) {
								price = item.udPrice
							}
							else {
								price = item.price
							}
							let { companyName, createTime, chineseName, authStatusName, quantity,
								payTypeName, deliveryTypeName, transportTypeName, destAddress, comments, intentionQuantity, select, udPrice
							} = item
							return (
								<View style={{ marginTop: 10 * scale }} key={index}>
									<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 * scale }}>
										<Text style={{ fontSize: 11 }}>{companyName}</Text>
										<Text style={{ fontSize: 11 }}>{createTime}</Text>
									</View>
									<View style={styles.offerDetailItem}>
										<View style={{ flexDirection: 'row', marginBottom: 16 * scale, paddingRight: 20 * scale, justifyContent: 'space-between' }}>
											<TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => this.changeCheck(index)}>
												<View style={styles.checkBox}>
													<View style={styles.lockView}>
														{
															select ? <Image style={styles.lockImage} source={correct} /> : null
														}
													</View>
												</View>
												<Text style={{ fontSize: 13, fontWeight: '600' }}>{chineseName}</Text>
											</TouchableOpacity>
											<Text style={{ fontSize: 11, color: '#E02020' }}>{authStatusName}</Text>
										</View>
										<View style={styles.offerDetailHorizontal}>
											<View style={styles.offerDetailBox}>
												{priceType == 1 ?
													<Text style={styles.offerDetailTitle}>含税单价</Text>
													: <Text style={styles.offerDetailTitle}>升贴水</Text>
												}
												{priceType == 1 ?
													<Text style={styles.offerDetailTopText}>{!Utils.isEmpty(price) ? '¥' + price + '/吨' : '-'}</Text>
													: <Text style={styles.offerDetailTopText}>{!Utils.isEmpty(udPrice) ? (udPrice > 0 ? '+' : '-') + '¥' + Math.abs(udPrice) + '/吨' : '-'}</Text>
												}
												{suggestedPrice && priceType == 1 ? <Image source={price - suggestedPrice > 0 ? upDegreen : downDegreen} style={styles.priceFlag} /> : null}
												{suggestedPrice && priceType == 1 ? <Text style={price - suggestedPrice > 0 ? styles.tableUpText : styles.tableDownText}>{Math.abs(price - suggestedPrice)}</Text> : null}
											</View>
										</View>
										<View style={styles.offerDetailHorizontal}>
											<View style={styles.offerDetailBox}>
												<Text style={styles.offerDetailTitle}>报盘量</Text>
												<Text style={styles.offerDetailText}>{quantity ? quantity + '吨' : '-'}</Text>
											</View>
											<View style={styles.offerDetailBox}>
												<Text style={styles.offerDetailTitle}>总金额</Text>
												<Text style={styles.offerDetailText}>{'¥' + MethodUtil.toThousands(quantity * price || 0, 2)}</Text>
											</View>
										</View>
										<View style={styles.offerDetailHorizontal}>
											<View style={styles.offerDetailBox}>
												<Text style={[styles.offerDetailTitle, { color: '#CA0202' }]}>*成交执行量</Text>
												<TextInput
													style={styles.textInput}
													underlineColorAndroid='transparent'
													keyboardType='numeric'
													editable={true}
													maxLength={100}
													placeholder={"请输入数字"}
													placeholderTextColor="#404040"
													defaultValue={intentionQuantity + ''}
													onChangeText={(val) => {
														this.data.appOrderDetailsVTOS[index].intentionQuantity = val
													}}
												/>
												<Text style={{ marginLeft: 10 * scale, fontSize: 12 * scale }}>吨</Text>
											</View>
										</View>
										{payTypeName || deliveryTypeName || transportTypeName || destAddress || comments ?
											<View style={{ backgroundColor: '#F4F7FE', borderRadius: 6, paddingHorizontal: 20 * scale, paddingVertical: 8 * scale }}>
												<Text style={{ color: '#979797', fontSize: 11 * scale, lineHeight: 24 * scale }}>{payTypeName ? payTypeName + '|' : ''}
													{deliveryTypeName ? deliveryTypeName : ''}
													{transportTypeName ? (deliveryTypeName ? '|' : '') + transportTypeName : ''}
													{destAddress ? (destAddress ? '|' : deliveryTypeName ? '|' : '') + '客户配送地址' + destAddress : ''}
												</Text>
												{comments ?
													<TouchableOpacity onPress={() => { this.setState({ isCommentsModal: true, comments: comments }) }}>
														<Text style={[styles.offerItemTitle, { color: '#0091FF', marginTop: 10 * scale }]}>
															[客户备注]
               					 </Text>
													</TouchableOpacity> : null
												}
											</View> : null
										}
									</View>
								</View>
							)
						})
							: null
						}
					</ScrollView>
				</View>
				<ApprovalCpt
					data={{ isAll, allText, isDetail: true }}
					method={{ selectAll: this._selectAll, refused: this._refused, agree: this._add }}
				/>
				<RefuseModal
					titleText={this.applyParams.applyInfo.applyType == 'ACCEPT' ? '成交理由' : '拒绝理由'}
					placeholderText={this.applyParams.applyInfo.applyType == 'ACCEPT' ? '请输入成交原因' : '请输入驳回原因'}
					visible={showRejectModal}
					text={this.priceCheckMsg}
					btnPress={(comments) => {
						this.applyParams.applyInfo.remark = comments;
						this.approve();
					}}
					bgPress={() => {
						this.setState({
							showRejectModal: false,
						});
					}} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	body: {
		flex: 1,
		backgroundColor: '#E8ECF5',
	},
	itemBox: {
		marginTop: 20 * scale,
		backgroundColor: '#fff',
		borderRadius: 6 * scale,
		marginHorizontal: 20 * scale
	},
	itemTop: {
		paddingVertical: 20 * scale,
		paddingRight: 10 * scale,
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		backgroundColor: '#fff'
	},
	itemTitle: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
	},
	itemTopLeft: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingLeft: 10 * scale
	},
	lockView: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		height: 12 * scale,
		width: 12 * scale,
		borderWidth: 1 * scale,
		borderColor: style.color.themeColor,
		marginRight: 10 * scale,
		marginLeft: 10 * scale
	},
	lockImage: {
		tintColor: style.color.themeColor,
		width: 8 * scale,
		height: 8 * scale,
		marginLeft: 1 * scale
	},
	imgStyle: {
		tintColor: '#000',
		width: 10 * scale,
		height: 6 * scale,
		transform: [{ rotate: '-90deg' }]
	},
	itemBottom: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		paddingVertical: 12 * scale,
		paddingHorizontal: 10 * scale,
	},
	priceType: {
		fontSize: 10 * scale,
		paddingVertical: 2 * scale,
		paddingHorizontal: 5 * scale,
		backgroundColor: '#FBEFE8',
		marginLeft: 5 * scale
	},
	titleText: {
		color: '#000',
		fontSize: 11 * scale,
		fontWeight: '600'
	},
	itemMiddle: {
		paddingVertical: 10 * scale,
		paddingHorizontal: 10 * scale,
	},
	priceFlag: {
		width: 6 * scale,
		height: 10 * scale,
		marginRight: 3 * scale
	},
	tableUpText: {
		fontSize: 10 * scale,
		color: '#E02020'
	},
	tableDownText: {
		fontSize: 10 * scale,
		color: '#56C910'
	},
	costTableRight: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	costItem: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingLeft: 56 * scale,
		marginTop: 13 * scale
	},
	costBox: {
		paddingVertical: 12 * scale,
		borderBottomWidth: 1 * scale,
		borderBottomColor: '#E3E7F0'
	},
	costTextLeft: {
		fontSize: 12 * scale,
		color: '#000',
		marginRight: 10 * scale
	},
	costNum: {
		fontSize: 12 * scale,
		color: '#000',
		opacity: 0.78,
		width: 50 * scale
	},
	costNumInput: {
		color: '#000',
		fontWeight: '600',
		width: 50 * scale
	},
	offerDetailBox: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	offerDetailTitle: {
		width: 68 * scale,
		textAlign: 'right',
		marginRight: 16 * scale,
		fontSize: 12,
		color: '#979797'
	},
	offerDetailText: {
		fontSize: 12 * scale,
		color: '#000',
		width: 50 * scale,
		marginRight: 30 * scale
	},
	offerDetailTopText: {
		fontSize: 12,
		color: '#000',
		marginRight: 10 * scale
	},
	offerDetailHorizontal: {
		flexDirection: 'row',
		paddingHorizontal: 20 * scale,
		// justifyContent:'space-between',
		marginBottom: 12 * scale
	},
	commentsBody: {
		width: 300 * scale,
		paddingLeft: 25 * scale,
		paddingRight: 17 * scale,
		paddingBottom: 30 * scale,
		backgroundColor: '#fff',
		borderRadius: 13 * scale
	},
	commentsTitle: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
		paddingTop: 15 * scale,
		paddingBottom: 15 * scale
	},
	commentContent: {
		fontSize: 12 * scale,
		paddingTop: 15 * scale,
		paddingBottom: 15 * scale
	},
	offerDetailItem: {
		backgroundColor: '#fff',
		paddingTop: 14 * scale,
		borderRadius: 6 * scale,
		marginBottom: 16 * scale
	},
	textInput: {
		width: 100 * scale,
		borderWidth: 1 * scale,
		borderColor: '#D5D5D5',
		fontSize: 12 * scale,
		textAlign: 'center',
		paddingVertical: 3 * scale
	}
})